import axios from 'axios'


/* 获取购物车商品列表以及计算商品总价格 */
export const actionInitCartList = () => {
  return dispatch => {
    window.localStorage.removeItem('cartList')
    axios.get('http://localhost:9000/cartList')
      .then(res => {
        let cartList = res.data

        if (cartList.length > 0) {
          window.localStorage.setItem('cartList', JSON.stringify(cartList))

          let list = cartList.map(item => {
            return item.goods_num * (item.goods_price * 100)
          })
          let totalPrice = ((list.reduce((prev, cur) => prev + cur)) / 100).toFixed(2)
          
          dispatch({
            type: 'mutationInitCartList',
            cartFlag: true,
            cartList,
            totalPrice
          })

        } else {
          dispatch({
            type: 'mutationInitCartList',
            cartFlag: false,
            totalPrice: '0.00',
            cartList: []
          })
        }
      })
  }
}

/* 点击加减按钮，修改仓库单个商品的数量 */
export const actionAdd = (goodsInfo, btnType) => {
  return dispatch => {
    let num = parseInt(goodsInfo.goods_num)
    goodsInfo.goods_num = (btnType === 'add') ? (num + 1 + '') : (num - 1 + '')
    
    dispatch({
      type: 'mutationAdd',
      goodsInfo,
      btnType
    })
  }
}

/* 删除购物车商品 */
export const actionDel = (id) => {
  return dispatch => {
    axios.delete(`http://localhost:9000/cartList/${id}`)
      .then(res => {
        dispatch(actionInitCartList())
      })
  }
}

/* 点击按钮修改仓库的 总价格 totalPrice */
export const actionChangePrice = (newTotalPrice) => {
  return dispatch => {
    dispatch({
      type: 'mutationChangePrice',
      newTotalPrice
    })
  }
}

/* 商品详情页 添加商品进购物车 */
export const actionAddGoods = (goodsInfo, storeName) => {
  return (dispatch) => {
    let list = JSON.parse(window.localStorage.getItem('cartList'))

    if (list) {
      let aaa = list.find(item => item.goods_id === goodsInfo.goods_id)

      if (aaa) {
        return 
      }
    }
    
    axios.post('http://localhost:9000/cartList', { ...goodsInfo })
      .then(res => {
        dispatch({
          type: 'mutationAddGoods',
          storeName
        })

        dispatch(actionInitCartList())
      })
  }
}
